package com.utils;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

public class Sound implements Runnable {
	
	public static final int STOPPED = -1000, PAUSED = -2000;
	
	public SoundPool pool;
	Context context;
	public int start;
	public int mid;
	public int end;
	int state;
	int section;
	float speed;
	float volume;
	Thread checkThread;
	
	public Sound(Context context) {
		this.context = context;
		this.pool = new SoundPool(1, AudioManager.STREAM_MUSIC, 100);
		this.speed = 0.9f;
		this.volume = 0.9f;
		this.state = Sound.STOPPED;
		this.checkThread = new Thread(this);
	}
	
	public void loadSounds(int start, int mid, int end) {
		this.start = pool.load(context, start, 3);
		this.mid = pool.load(context, mid, 2);
		this.end = pool.load(context, end, 1);
		
		this.section = start;
	}
	
	public void unloadSounds() {
		pool.unload(start);
		pool.unload(mid);
		pool.unload(end);
	}
	
	public void play() {
		if(state == Sound.STOPPED) {
			Log.i("PARP","Playing from stop");
			pool.play(start, volume, volume, 3, 0, speed);
			state = start;
			if(!checkThread.isAlive()) {
				checkThread.run();
			}
		} else if(state == Sound.PAUSED) {
			Log.i("PARP","Playing from pause");
			pool.resume(section);
			state = section;
			if(!checkThread.isAlive()) {
				checkThread.run();
			}
		}
	}
	
	public void pause() {
		if(state != Sound.STOPPED && state != Sound.PAUSED) {
			Log.i("PARP","Pausing");
			if(checkThread.isAlive()) {
				checkThread.stop();
			}
			pool.pause(state);
			section = state;
			state = Sound.PAUSED;
		}
	}
	
	public void stop() {
		if(state != Sound.STOPPED) {
			/*Log.i("PARP","Stopping at state + " + state + " " + mid);
			if(checkThread.isAlive()) {
				checkThread.stop();
			}
			pool.setLoop(state, 0);
			state = end;
			if(!checkThread.isAlive()) {
				checkThread.run();
			}*/
			pool.pause(state);
			state = Sound.STOPPED;
		}
	}
	
	public void run() {
		while(state == start/* || state == end*/) {
			int finished = 0;
			if(state == start){
				//Wait till can play mid sound
				finished = pool.play(mid, volume, volume, 2, -1, speed);
				if(finished != 0) {
					Log.i("PARP","Playing mid after start");
					state = mid;
				}
			}/* else if(state == end) {
				//Wait till can play end sound
				finished = pool.play(end, volume, volume, 1, 0, speed);
				if(finished != 0) {
					Log.i("PARP","Playing end after mid");
					state = Sound.STOPPED;
				}
			}*/
		}
	}
}
